<template>
  <div class="box">
    <hu-card :pb='0' v-show="MixinSelectShow">
      <el-form :model="queryParams" label-width="70px">
        <el-row :gutter="50">
          <el-col :span="6">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="queryParams.name" type="text" placeholder="请输入角色名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间" prop="ctimeStart">
              <el-date-picker v-model="queryParams.ctimeStart" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="searchFromButton">
              <el-button type="primary" icon="el-icon-search" @click="MixinSearchList">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="MixinResetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </hu-card>

    <hu-card>
      <el-row :gutter="10" class="mb10 space_between" type="flex">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" @click="addClick">新增</el-button>
          <el-button icon="el-icon-delete" type="danger" @click="handleAllDelete">批量删除</el-button>
        </el-col>
        <right-toolbar :tableCol.sync="tableCol" :showSearch.sync="MixinSelectShow" @queryTable="getList"></right-toolbar>
      </el-row>
      <hu-table :tableData="tableData" :loading="MixinLoading" :tableCol="tableCol" @selection-change="handleSelectionChange">
        <template v-slot:userCount="{ row }">
          <el-button type="text" @click="handleUpdate(row)">{{row.userCount}}</el-button>
        </template>
        <template v-slot:operate="{ row }">
          <span @click="editClick(row)" style="font-size: 14px; color: #5a8bff; cursor: pointer">修改</span>
          <el-divider direction="vertical"></el-divider>
          <span @click="errClick(row)" style="font-size: 14px; color: #5a8bff; cursor: pointer">删除</span>
        </template>
      </hu-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </hu-card>
    <!-- 修改项目对话框 -->

    <hu-modal ref="designDialog" :title="title" :show-modal.sync="dialogVisible" :loading="MixinLoading" @close="setRoleShow" @submit="ok('form')">
      <el-form :model="form" ref="form" class="mt10" :rules="rules" label-width="110px">
        <el-row :gutter="50">
          <el-col :span="8">
            <el-form-item label="角色名称" required prop="name">
              <el-input v-model="form.name" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="权限字符" required prop="value">
              <el-input v-model="form.value" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" required prop="sort">
              <el-input-number v-model="form.sort" style="width:100%" controls-position="right"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="50">
          <el-col :span="8">
            <el-form-item label="状态" required prop="status">
              <el-radio-group v-model="form.status" style="width: 100%">
                <el-radio :label="0">启用</el-radio>
                <el-radio :label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注" prop="specification">
              <el-input v-model="form.specification" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="treeBorder">
        <el-tree :data="treedata" ref="tree" accordion show-checkbox :check-strictly="strictly" node-key="id" :default-checked-keys="checktree" :filter-node-method="filterNode" :props="defaultProps">
        </el-tree>
      </div>
    </hu-modal>
    <hu-modal title="用户-角色列表" :show-modal.sync="showUserList" :loading="MixinLoading" :submit="false">
      <hu-card :pb='0' v-show="MixinSelectShow">
        <el-form :model="queryParams2" label-width="70px">
          <el-row :gutter="50">
            <el-col :span="6">
              <el-form-item label="工号" prop="code">
                <el-input v-model="queryParams2.code" type="text" placeholder="请输入工号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="queryParams2.name" type="text" placeholder="请输入姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="部门" prop="deptId">
                <el-select v-model="queryParams2.deptId" placeholder="请输入部门">
                  <el-option v-for="dict in dictsList" :key="dict.id" :value="dict.id" :label="dict.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item class="searchFromButton">
                <el-button type="primary" icon="el-icon-search" @click="getListIndex2">查询</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-button icon="el-icon-delete" style="margin-bottom: 20px;" type="danger" @click="handleAllDelete2">批量移除</el-button>
        <hu-table :tableData="userList" :loading="MixinLoading" :tableCol="tableCol2" @selection-change="handleSelectionChange2">
          <template v-slot:operate="{ row }">
            <el-button type="text" @click="errClick2(row)">移除</el-button>
          </template>
        </hu-table>
        <pagination v-show="total2 > 0" :total="total2" :page.sync="queryParams2.pageNum" :limit.sync="queryParams2.pageSize" @pagination="getList2" />
      </hu-card>
    </hu-modal>
  </div>
</template>

<script>
import {
  treeAdd,
  treeEdit,
  treeDel,
  treeDel2,
  roleTreeList,
  getList,
  getList2,
  roleEditTree,
} from "@/api/system/role";
export default {
  name: "SystemRole",
  data() {
    return {
      dictsList: [],
      strictly: true,
      treedata: [],
      checktree: [],
      loading: false,
      fatherShow: false,
      currentRowId: "",
      title: "添加权限",
      multipleSelection: [],

      resourcesIds: [],
      dictionaries: { chengbaoshangleibie: [] },
      dialogVisible: false,
      searchData: {
        name: null,
        contractorType: null,
        serviceType: null,
        qualificationsLevel: null,
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      total2: 0,
      tableCol: [
        {
          type: "selection",
          width: "55",
        },
        {
          title: "角色名称",
          key: "name",
          minWidth: 100,
        },
        {
          title: "权限字符",
          key: "value",
        },
        {
          title: "排序",
          key: "sort",
        },
        {
          title: "用户列表(个)",
          slot: "userCount",
        },
        {
          title: "创建人",
          key: "cuser",
        },
        {
          title: "创建时间",
          key: "ctime",
        },
        {
          title: "操作",
          slot: "operate",
          width: 210,
        },
      ],
      tableCol2: [
        {
          type: "selection",
          width: "55",
        },
        {
          title: "序号",
          type: "index",
        },
        {
          title: "工号",
          key: "code",
        },
        {
          title: "姓名",
          key: "name",
        },
        {
          title: "联系电话",
          key: "phoneNo",
        },
        {
          title: "部门",
          key: "deptName",
        },
        {
          title: "班组",
          key: "teamName",
        },
        {
          title: "角色",
          key: "roleName",
        },
        {
          title: "操作",
          slot: "operate",
          width: 210,
        },
      ],
      tableData: [],
      form: {
        name: "",
        names: "",
        code: "",
        value: "",
        status: 0,
        sort: 0,
      },
      rules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        value: [{ required: true, message: "请输入权限字符", trigger: "blur" }],
      },
      filterText: "",
      defaultProps: {
        children: "children",
        label: "name",
      },
      // list 参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 10,
      },
      showUserList: false,
      userList: [],
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted() {
    this.$refs.designDialog.$children[0].rendered = true;
    this.getDicts();
    this.getList();
  },
  methods: {
    // 部门
    getDicts() {
      this.$http.getDicts().then(({ result }) => {
        this.dictsList = result;
      });
    },
    handleUpdate(row) {
      this.showUserList = true;
      this.queryParams2.roleId = row.id;
      this.getList2();
    },
    getListIndex2() {
      this.queryParams2.pageNum = 1;
      this.getList2();
    },
    getList2() {
      this.MixinLoading = true;
      let params = {
        ...this.queryParams2,
      };
      getList2(params).then(({ stateCode, result }) => {
        if (stateCode == 200) {
          this.MixinLoading = false;
          this.userList = result.records;
          this.total2 = result.total;
        }
      });
    },


    setRoleShow() {
      this.resetForm("form");
      this.strictly = true;
    },
    handleCheckChange() {
      this.MixinLoading = true;
      this.roleEditStr.resourceIds = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys(),
      ];
      this.loading = true;
      roleEditTree(this.roleEditStr).then((res) => {
        if (res.stateCode == 200) {
          // this.$message({
          //   message: "权限修改成功",
          //   type: "success",
          // });

          this.getList();
          this.setRoleShow();
          this.loading = false;
        }
        this.MixinLoading = false;
      });
    },
    loadNode(node, resolve) {},
    currentRow(row) {},
    // 列表 List
    getList() {
      this.MixinLoading = true;
      let params = {
        ...this.queryParams,
        ctimeStart:
          this.queryParams.ctimeStart &&
          this.queryParams.ctimeStart[0] + " 00:00:00",
        ctimeEnd:
          this.queryParams.ctimeStart &&
          this.queryParams.ctimeStart[1] + " 23:59:59",
      };
      getList(params).then(({ stateCode, result }) => {
        if (stateCode == 200) {
          this.MixinLoading = false;
          this.tableData = result.records;
          this.total = result.total;
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((e) => e.id);
    },
    handleSelectionChange2(val) {

      this.resourcesIds = val.map((e) => e.userId);
    },
    treeClick(val) {
      this.form.parentCode = val.code;
      this.form.names = val.name;
    },
    deepClone(object) {
      let str;
      let newobj = object.constructor === Array ? [] : {};
      if (typeof object !== "object") {
        return object;
      } else if (window.JSON) {
        str = JSON.stringify(object);
        newobj = JSON.parse(str);
      } else {
        for (const i in object) {
          if (Object.prototype.hasOwnProperty.call(object, object[i])) {
            newobj[i] =
              typeof object[i] === "object"
                ? this.deepClone(object[i])
                : object[i];
          }
        }
      }
      return newobj;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    onSubmit() {},
    resetForm(formName) {
      this.dialogVisible = false;
      this.$refs[formName].resetFields();
    },
    ok(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          delete this.form.children;
          this.MixinLoading = true;
          if (this.formSubmit) {
            treeAdd(this.form).then((res) => {
              if (res.stateCode == 200) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });

                this.getList();
                this.dialogVisible = false;
                this.$refs["form"].resetFields();
              } else {
                this.$message({
                  message: res.message,
                  type: "error",
                });
              }
              this.MixinLoading = false;
            });
          } else {
            treeEdit(this.form).then((res) => {
              if (res.stateCode == 200) {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });

                this.dialogVisible = false;
                this.handleCheckChange();
                this.getList();
                this.$refs["form"].resetFields();
              } else {
                this.$message({
                  message: res.message,
                  type: "error",
                });
              }
              this.MixinLoading = false;
            });
          }
        } else {
          return false;
        }
      });
      return;
    },
    cancel() {
      this.$Message.info("Clicked cancel");
    },
    handleAllDelete() {
      if (!this.multipleSelection.length) return this.$modal.msg("请勾选表格");
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(() => {
          this.multipleSelection.forEach((e) => {
            treeDel(e).then((e) => {
              this.getList();
            });
          });
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleAllDelete2() {
      if (!this.resourcesIds.length) return this.$modal.msg("请勾选表格");
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(() => {
          return treeDel2({
            roleId: this.queryParams2.roleId,
            userIds: this.resourcesIds,
          });
        })
        .then(() => {
          this.getList2()
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    reset() {
      this.form = {
        name: "",
        names: "",
        code: "",
        value: "",
        status: 0,
        sort: 0,
      };
    },
    addClick() {
      this.reset();
      this.title = "添加权限";
      this.formSubmit = true;
      this.dialogVisible = true;
    },
    editClick(row) {
      this.form = { ...row, names: "" };
      this.formSubmit = false;
      this.title = "修改角色";
      this.roleEditStr = {
        roleId: row.id,
        resourceIds: [],
      };
      roleTreeList(row.id).then((res) => {
        if (res.stateCode == 200) {
          this.treedata = [res.result.webResourceTree];
          this.checktree = [
            ...res.result.webSelectedResourceIds,
            ...res.result.appSelectedResourceIds,
          ];
          this.$nextTick(() => {
            this.dialogVisible = true;
            this.strictly = false;
          });
        }
      });
    },
    errClick(row) {
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(() => {
          return treeDel(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    errClick2(row) {
      this.$modal
        .confirm("是否确认移除数据项？")
        .then(() => {
          return treeDel2({
            roleId: this.queryParams2.roleId,
            userIds: [row.userId],
          });
        })
        .then(() => {
          this.getListIndex2();
          this.$modal.msgSuccess("移除成功");
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.top-search {
  background-color: white;
  padding: 30px;
  margin-bottom: 20px;
  border-radius: 3px;
}
.changeSlot:hover {
  cursor: pointer;
}
.box-content {
  padding: 30px;
  background-color: white;
  border-radius: 3px;
}
.treeBorder {
  width: 100%;
  margin: 15px auto;
  padding: 10px;
  border: rgb(241, 239, 239) solid 0.5px;
}
.el-radio__input.is-checked + .el-radio__label {
  color: #fff !important;
}
.box {
  height: 100%;
}
</style>
